package com.doctor.windflower_doctor.activity;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.doctor.windflower_doctor.R;
import com.doctor.windflower_doctor.actionBeen.UserControlBeen;
import com.doctor.windflower_doctor.adapter.TenantServiceAdapter;
import com.doctor.windflower_doctor.db.SharedPreferencesDB;
import com.doctor.windflower_doctor.entity.UserBeen;
import com.doctor.windflower_doctor.myuser.tools.HttpclientHelper;
import com.doctor.windflower_doctor.util.Constent;
import com.doctor.windflower_doctor.view.LoadingDialog;
import com.doctor.windflower_doctor.view.PullToCustomListView;
import com.doctor.windflower_doctor.view.PullToCustomListView.OnAutoLoadBottomListener;
import com.doctor.windflower_doctor.view.PullToCustomListView.OnRefreshDownListener;

public class TenantService extends BaseActivity implements Constent {
	private List<UserControlBeen> groupName;
	private PullToCustomListView cuto_listView;
	private String id;
	private List<UserBeen> list;
	private TenantServiceAdapter adapter;
	private String name;
	private Button move_Button;
	private SharedPreferencesDB db;
	private RelativeLayout relativeLayout;
	private Button tryAgainButton;
	private LoadingDialog loadingDialog;
	private TextView textView, tv_save;
	private ImageButton orenge_btn, back_btn;

	@Override
	protected void getSaveData(Bundle savedInstanceState) {
		// TODO Auto-generated method stub

	}

	@Override
	protected void processLogic() {
		// TODO Auto-generated method stub

	}

	@Override
	protected void setListener() {
		// TODO Auto-generated method stub
		tryAgainButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				new UserMessage_asynck().execute(URL + ALL_URL + "?groupId="
						+ id + "&size=" + "20" + "&doctorId="
						+ db.getDocotorId());
			}
		});
		back_btn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
			}
		});

		orenge_btn.setOnClickListener(new OnClickListener() {
			@SuppressLint("NewApi")
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (adapter != null) {
					orenge_btn.setVisibility(View.GONE);
					adapter.setShow(true);
					tv_save.setVisibility(View.VISIBLE);
					tv_save.setText("取消");
				} else {
					orenge_btn.setVisibility(View.VISIBLE);
					tv_save.setVisibility(View.GONE);
				}
			}
		});
		tv_save.setOnClickListener(new OnClickListener() {

			@SuppressLint("NewApi")
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (adapter != null) {
					adapter.setShow(false);
					orenge_btn.setVisibility(View.VISIBLE);
					tv_save.setVisibility(View.GONE);
				} else {
					orenge_btn.setVisibility(View.VISIBLE);
					tv_save.setVisibility(View.GONE);
				}
			}
		});

		cuto_listView.setOnRefreshDownListener(new OnRefreshDownListener() {

			@Override
			public void onRefresh() {
				// TODO Auto-generated method stub
				new UserMessage_Asynck_Pull_Down().execute(URL + ALL_URL
						+ "?groupId=" + id + "&size=" + "20" + "&doctorId="
						+ db.getDocotorId());
			}
		});
		cuto_listView.onItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				Bundle bundle = new Bundle();
				bundle.putString("USERID", adapter.getPosition(position)
						.getUserId());
				startActivity(new Intent(TenantService.this,
						SickDetailActivity.class).putExtras(bundle));

			}
		});

		cuto_listView
				.setOnAutoLoadBottomListener(new OnAutoLoadBottomListener() {

					@Override
					public void onBottomLoad() {
						// TODO Auto-generated method stub

						new UserMessage_Asynck_Pull_Up().execute(URL
								+ ALL_URL
								+ "?groupId="
								+ id
								+ "&size="
								+ "15"
								+ "&doctorId="
								+ db.getDocotorId()
								+ "&userId="
								+ adapter.getlist()
										.get(adapter.getlist().size() - 1)
										.getUserId());

					}
				});

	}

	@SuppressWarnings("unchecked")
	@Override
	protected void findViews() {
		// TODO Auto-generated method stub
		relativeLayout = (RelativeLayout) findViewById(R.id.nowifi_layout);
		tryAgainButton = (Button) findViewById(R.id.try_again);
		loadingDialog = new LoadingDialog(TenantService.this);
		textView = (TextView) findViewById(R.id.textView);
		tv_save = (TextView) findViewById(R.id.tv_save);
		textView.setText("用户分组");
		tv_save.setText("取消");
		orenge_btn = (ImageButton) findViewById(R.id.orenge_btn);
		orenge_btn.setVisibility(View.VISIBLE);
		back_btn = (ImageButton) findViewById(R.id.back_btn);
		orenge_btn.setImageDrawable(this.getResources().getDrawable(
				R.drawable.edit_button));
		move_Button = (Button) findViewById(R.id.move_button);
		Intent intent = getIntent();
		id = intent.getExtras().getString("id");
		name = intent.getExtras().getString("name");
		textView.setText(name);
		groupName = (List<UserControlBeen>) intent.getExtras().getSerializable(
				"arr");
		for (int i = 0; i < groupName.size(); i++) {
			if (groupName.get(i).getGroupName().equals(name)) {
				groupName.remove(i);
			}
		}
		cuto_listView = (PullToCustomListView) findViewById(R.id.listView1);
		db = SharedPreferencesDB.getInstance(TenantService.this);
		new UserMessage_asynck().execute(URL + ALL_URL + "?groupId=" + id
				+ "&size=" + "20" + "&doctorId=" + db.getDocotorId());

	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();

	}

	@Override
	public int getResLayoutId() {
		// TODO Auto-generated method stub
		return R.layout.tenant_service;
	}

	class UserMessage_asynck extends AsyncTask<String, Void, String> {
		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			loadingDialog.show();
		}

		@Override
		protected String doInBackground(String... params) {
			// TODO Auto-generated method stub
			return HttpclientHelper.clientGet(params[0]);
		}

		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			if (result != null) {
				relativeLayout.setVisibility(View.INVISIBLE);
				cuto_listView.setVisibility(View.VISIBLE);
				list = userMessage_Json(result);
				if (list != null) {
					adapter = new TenantServiceAdapter(TenantService.this,
							list, groupName, move_Button);
					cuto_listView.setAdapter(adapter);
				} else {
					Toast.makeText(TenantService.this, "获取数据失败",
							Toast.LENGTH_SHORT).show();
				}

			} else {
				relativeLayout.setVisibility(View.VISIBLE);
				cuto_listView.setVisibility(View.INVISIBLE);
				Toast.makeText(TenantService.this, "请检查网络状态",
						Toast.LENGTH_SHORT).show();
			}
			loadingDialog.close();
		}
	}

	class UserMessage_Asynck_Pull_Up extends AsyncTask<String, Void, String> {

		@Override
		protected String doInBackground(String... params) {
			// TODO Auto-generated method stub
			return HttpclientHelper.clientGet(params[0]);
		}

		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			if (result != null) {
				list = userMessage_Json(result);

				if (list.size() != 0) {
					adapter.listAddAll(list);
				} else {
					Toast.makeText(TenantService.this, "已到底部",
							Toast.LENGTH_SHORT).show();
					cuto_listView.onLoadBottomEnd();
				}

			} else {
				Toast.makeText(TenantService.this, "请检查网络状态",
						Toast.LENGTH_SHORT).show();
			}
			cuto_listView.onLoadBottomComplete();
		}

	}

	class UserMessage_Asynck_Pull_Down extends AsyncTask<String, Void, String> {

		@Override
		protected String doInBackground(String... params) {
			// TODO Auto-generated method stub
			return HttpclientHelper.clientGet(params[0]);
		}

		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			if (result != null) {

				List<UserBeen> list = userMessage_Json(result);
				if (list != null) {
					adapter.listClear();
					adapter.listAddOne(list);

				} else {
					Toast.makeText(TenantService.this, "没有新的数据",
							Toast.LENGTH_SHORT).show();
				}

			} else {
				Toast.makeText(TenantService.this, "请检查网络状态",
						Toast.LENGTH_SHORT).show();
			}
			cuto_listView.onRefreshDownComplete();
		}
	}

	public List<UserBeen> userMessage_Json(String json) {
		JSONObject jsonObject;

		try {
			jsonObject = new JSONObject(json);
			if (jsonObject.getBoolean("success")) {
				List<UserBeen> list = new ArrayList<UserBeen>();
				JSONObject jsonObject2 = jsonObject.getJSONObject("data");
				JSONArray jsonArray = jsonObject2.getJSONArray("users");
				for (int i = 0; i < jsonArray.length(); i++) {
					JSONObject jsonObject3 = jsonArray.getJSONObject(i);
					UserBeen userBeen = new UserBeen();
					userBeen.setAge(jsonObject3.getString("age"));
					userBeen.setCondition(jsonObject3.getString("condition"));
					userBeen.setImgUrl(jsonObject3.getString("imgUrl"));
					userBeen.setNick(jsonObject3.getString("nick"));
					userBeen.setPrePeriod(jsonObject3.getString("prePeriod"));
					userBeen.setRemark(jsonObject3.getString("remark"));
					userBeen.setUserId(jsonObject3.getString("userId"));
					list.add(userBeen);

				}
				return list;
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;

	}
}
